package co.edu.icesi.sca.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.io.PrintWriter;

public class ClientListener implements Runnable
{
    private Client client;
    public ClientListener(Client client)
    {
        this.client = client;
    }
    
    @Override
    public void run( )
    {
        execute( System.in, System.out );
    }
    
    public void execute(InputStream inputStream, OutputStream outputStream)
    {
        
        final LineNumberReader reader = new LineNumberReader(
                new InputStreamReader(inputStream));
        final PrintWriter writer = new PrintWriter(outputStream);
        
        String line;
        while ((line = read(reader)) != null)
        {
            line = line.trim();

            /* Ignore blank lines */
            if (line.length() == 0)
            {
                writer.flush();
                continue;

            }
            else
            {
                client.sendMessage( line );
                System.out.println("Message sent:"+ line);
            }
        }
    }
        
        private String read(LineNumberReader reader)
        {
            try
            {
                return reader.readLine();
            }
            catch (IOException ioe)
            {
                throw new RuntimeException("I/O error at line "
                        + reader.getLineNumber() + ": " + ioe.getMessage(), ioe);
            }
        }
}
